package com.ytktt.study.week9.task3.rpcfx.client.transport.netty;

import com.ytktt.study.week9.task3.rpcfx.api.RpcfxResponse;
import com.ytktt.study.week9.task3.rpcfx.enums.ErrResponseEnum;
import com.ytktt.study.week9.task3.rpcfx.exception.RpcfxException;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.util.concurrent.CountDownLatch;

/**
 * TODO
 *
 * @author ytk
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private RpcfxResponse result;
    private final CountDownLatch cdl = new CountDownLatch(1);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            this.result = (RpcfxResponse) msg;
//            FullHttpMessage fullHttpMessage = (FullHttpMessage) msg;
//            String respJson = fullHttpMessage.content().toString(CharsetUtil.UTF_8);
//            this.result = JSON.parseObject(respJson, new TypeReference<RpcfxResponse<T>>(clazz) {});
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cdl.countDown();
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    public RpcfxResponse getResult() {
        try {
            cdl.await();
        } catch (InterruptedException e) {
            throw new RpcfxException(ErrResponseEnum.FETCH_RESPONSE_FAIL);
        }
        return this.result;
    }
}
